import random
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
import itertools
from .ElementWise import ElementWise

class BitShift(ElementWise):
    cs_attributes = CS.ConfigurationSpace()
    attribute_list = ['direction']
    all_attributes = []

    def __init__(self):
        print('BitShift Init--------------------------')
        self.init_all_attributes()
        self.init_cs()

    def init_all_attributes(self):
        for i in range(1, len(BitShift.attribute_list)+1) :
            #此处取所有组合的可能值，存在列表里
            for attribute in itertools.combinations(BitShift.attribute_list, i):
                l = list(attribute)
                BitShift.all_attributes.append(l)

        #print('all_attributes: ', all_attributes)
        print('all attributes:')
        for a in BitShift.all_attributes:
            print(a)

    def init_cs(self):
        length = len(BitShift.all_attributes)
        attributes = CSH.UniformIntegerHyperparameter(name='combination', lower=0, upper=length)
        BitShift.cs_attributes.add_hyperparameter(attributes)

    def get_random_combination(self):
        s = BitShift.cs_attributes.sample_configuration()
        index = s.get_dictionary()['combination']
        print('get combination: ', index)

        length = len(BitShift.all_attributes)

        #保证不带任何属性的case可以被覆盖到
        if index >= length:
            index = length - 1

        return BitShift.all_attributes[index]       

    def get_max_attributes_combination(self):
        return len(BitShift.all_attributes)

    def get_attributes_by_index_or_random(self, shapes, index):

        print('get_attributes_by_index_or_random, index: ', index)    
            
        attributes = {}
        shape_out = []

        print('BitShift, shapes:', shapes[0])

        direction_int = 0

        if index != -1:
            attr_combination = BitShift.all_attributes[index]
        else:
            attr_combination = self.get_random_combination()

        if 'direction' in attr_combination:
            direction_int = random.randint(0, 1)
            if direction_int == 0:
                attributes['direction'] = 'LEFT'
            elif direction_int == 1:
                attributes['direction'] = 'RIGHT'   

        print('------ attributes:', attributes, 'shape_out:', shape_out)

        return attributes, shape_out 

